/*
 * Copyright 2014 Jonathan Haas
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package app.grinreader.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import app.grinreader.R;
import app.grinreader.library.Library;

import java.io.IOException;

public class LibraryActivity extends Activity {

    private GridView gridView;
    private Library library;

    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.library);
        library = new Library(this);
        Intent intent = getIntent();
        Log.d("intent",intent.toString());
        try {
            if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                Uri data = intent.getData();
                library.importBook(data);
                finish();
            }
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        gridView = (GridView) findViewById(R.id.gridView);
        final LibraryGridAdapter adapter = new LibraryGridAdapter(this, library, gridView);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String bookFile = adapter.getItem(position);
                Intent readIntent = new Intent(LibraryActivity.this, ReadActivity.class);
                readIntent.putExtra(ReadActivity.EXTRA_BOOK_FILE, bookFile);
                startActivity(readIntent);
            }
        });
    }

    public void onClearThumbs(MenuItem menuItem){
        library.clearCache();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.library, menu);
        return super.onCreateOptionsMenu(menu);
    }
}
